package com.gl.codewar.template;

import java.util.TreeMap;

public class MakingWaves {

	public static String surf(String str) {
            TreeMap<Integer, StringBuilder> wave = new TreeMap<Integer, StringBuilder>();
            
            char[] chars = str.toCharArray();
            int currentLine = 0;
            
            for(int i = 0; i < chars.length; i++) {
                if ( i == 0 ) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(chars[i]);
                    wave.put(0, sb);
                } else {
                    int delta = Character.compare(chars[i], chars[i-1]);
                    if ( delta > 0 ) {
                        delta = -1;
                    } else if (delta < 0) {
                        delta = 1;
                    }
                    currentLine += delta;
                    StringBuilder sb = wave.get(currentLine);
                    if ( sb == null ) {
                        sb = new StringBuilder();
                        for(int sp = 0; sp < i; sp ++) {
                            sb.append(" ");
                        }
                        wave.put(currentLine, sb);
                    } else{
                      while( sb.length() < i) {
                          sb.append(" ");
                      }
                    } 
                    
                    sb.append(chars[i]);
                }
                
            }
            
            StringBuilder waveStr = new StringBuilder();
            for (StringBuilder lines : wave.values()) {
                waveStr.append(lines).append("\n");
            }
		return waveStr.toString();
	}
        

}
